<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.productId" clearable :placeholder="$t('tracibility.productId')" style="width: 250px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.productSn" clearable :placeholder="$t('tracibility.productSn')" style="width: 250px;" class="filter-item" @keyup.enter.native="handleFilter" /><el-checkbox v-model="listQuery.state" class="filter-item" style="margin-left:15px;">
        {{ $t('common.match') }}
      </el-checkbox>
      <br>
      <el-input v-model="listQuery.processNumber" clearable :placeholder="$t('equipment.processNumber')" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.bomCode" clearable :placeholder="$t('bom.bomCode')" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.bomName" clearable :placeholder="$t('bom.bomName')" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model="listQuery.startTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('common.startDate')" class="filter-item" />
      <el-date-picker v-model="listQuery.endTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('common.endDate')" class="filter-item" />
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('common.export') }}
      </el-button>
    </div>
    <!-- 主界面数据 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :header-row-style="{color: 'black'}"
      :header-cell-style="{background: 'lightBlue'}"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column :label="$t('tracibility.productId')" width="220px" align="center">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleCheckProcess(row.part)">{{ row.part.productId }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('tracibility.productSn')" width="220px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.part.productSn }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.lineNumber')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.part.lineNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.stationNumber')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.part.stationNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.processNumber')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.part.processNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('bom.bomName')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.bomName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('bom.bomCode')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.bomCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('bom.bomValue')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.bomValue }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('bom.bomLot')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.bomLot }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('bom.bomQty')" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.bomQty }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('tracibility.testTime')" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" sortable="custom" prop="testTime" width="220px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.testTime }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('bom.bomState')" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="bomState[row.bomState].color">{{ bomState[row.bomState].label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="editRight" :label="$t('common.operation')" align="center" width="100px" class-name="small-padding fixed-width">
        <template slot-scope="{row, $index}">
          <transition name="fade">
            <el-button v-if="row.bomState === 0" type="primary" size="mini" @click="handleUnbound(row, $index)">
              {{ $t('common.unbound') }}
            </el-button>
          </transition>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import { getBomResultList, updateBomStatus } from '@/api/bom'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import i18n from '@/lang'

export default {
  name: 'BomSummary',
  components: {
    Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      editRight: true,
      tableKey: 0,
      list: [],
      total: 0,
      // 物料状态
      bomState: [
        { label: '新建', key: 0, color: '' },
        { label: '解绑', key: 1, color: 'danger' },
        { label: '临时', key: 2, color: 'warning' }
      ],
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        state: false,
        productSn: '',
        productId: '',
        bomCode: '',
        bomName: '',
        processNumber: '',
        lineNumber: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+test_time'
      },
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        lineName: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        lineNo: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        priority: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }]
      },
      downloadLoading: false,
      searchLoading: {
        company: false,
        manager: false
      },
      searchDialogStatus: '',
      searchDialogFormVisible: {
        company: false,
        manager: false
      }
    }
  },
  watch: {
    $route: {
      handler(val) {
        if (this.$route.query.productId !== undefined) {
          this.listQuery.productId = this.$route.query.productId
          this.getList()
        }
      }
    }
  },
  created() {
    // this.getList()
    this.listQuery.lineNumber = this.$store.getters.lineNumber
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
  },
  methods: {
    formatDateTime(date) {
      return date.substring(0, 10)
    },
    // 查看工艺结果清单
    handleCheckProcess(row) {
      const ret = Object.assign({}, row) // copy obj
      this.$router.push({ path: '/bom/bomProcessSummary', query: { productId: ret.productId }})
    },
    // 点击解绑
    handleUnbound(row, index) {
      this.$confirm(i18n.t('msg.UNBOUND_BOM_CONFIRM'), i18n.t('common.warn'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      })
        .then(async() => {
          this.list[index].bomState = 1
          this.temp = Object.assign({}, row) // copy obj
          updateBomStatus(this.temp).then(() => {
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.UNBOUND_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        })
        .catch(err => { console.error(err) })
    },
    // 获取清单
    getList() {
      this.listLoading = true
      getBomResultList(this.listQuery).then(response => {
        this.list = response.data.bomResults
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 排序时调用
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'startDate') {
        this.sortByCreatTime(order)
      } else if (prop === 'dueDate') {
        this.sortBydueDate(order)
      } else if (prop === 'priority') {
        this.sortByPriority(order)
      }
    },
    // 根据创建时间排序
    sortByCreatTime(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+start_date'
      } else {
        this.listQuery.sort = '-start_date'
      }
      this.handleFilter()
    },
    // 根据交期排序
    sortBydueDate(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+due_date'
      } else {
        this.listQuery.sort = '-due_date'
      }
      this.handleFilter()
    },
    // 根据优先级
    sortByPriority(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+priority'
      } else {
        this.listQuery.sort = '-priority'
      }
      this.handleFilter()
    },
    // 初始化创建信息
    resetTemp() {
      this.temp = {
        id: 0,
        projectNo: '',
        description: '',
        priority: '',
        manager: '',
        dueDate: '',
        startDate: '',
        state: 0,
        remark: '',
        companyCode: ''
      }
    },
    // 下载所有导出信息
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          i18n.t('tracibility.productId'),
          i18n.t('tracibility.productSn'),
          i18n.t('equipment.lineNumber'),
          i18n.t('equipment.stationNumber'),
          i18n.t('equipment.processNumber'),
          i18n.t('bom.bomCode'),
          i18n.t('bom.bomName'),
          i18n.t('bom.bomValue'),
          i18n.t('bom.bomLot'),
          i18n.t('tracibility.testTime')]
        const filterVal = ['productId', 'productSn', 'lineNumber',
          'stationNumber', 'processNumber', 'bomCode', 'bomName',
          'bomValue', 'bomLot', 'testTime']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '物料结果' + parseTime(Date.now(), '{y}{m}{d}{h}{i}{s}')
        })
        this.downloadLoading = false
      })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map((j, index) => {
        if (index < 5) {
          return v.part[j]
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }
.fade-leave-active {
  transition: opacity 2s;
}
  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
